package org.example.spring.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * LuoYu
 * 2022/12/13 18:45
 **/
public class TransactionUtil {


    private static final Logger LOGGER = LoggerFactory.getLogger(TransactionUtil.class);

    private static PlatformTransactionManager transactionManager;


    public static void setTransactionManager(PlatformTransactionManager transactionManager) {
        if(transactionManager != null) {
            LOGGER.info("获取到事务管理器实例,可根据TransactionUtil.PlatformTransactionManager  用于手动开启事务");
        }
        TransactionUtil.transactionManager = transactionManager;
    }



    public static PlatformTransactionManager getTransactionManager() {
        return TransactionUtil.transactionManager;
    }




    public static TransactionStatus getTransactionStatus() {
        return transactionManager.getTransaction(new DefaultTransactionDefinition());
    }

    /**
     *
     * @param transactionLevel   {@link TransactionDefinition}
     * @return
     */
    public static TransactionStatus getTransactionStatus(int transactionLevel) {
        // 默认的事务隔离级别
        if(transactionLevel == 0) {
            return getTransactionStatus();
        }
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        transactionDefinition.setPropagationBehavior(transactionLevel);
        return transactionManager.getTransaction(transactionDefinition);
    }

















}
